import base64

from captcha.views import CaptchaStore, captcha_image
from drf_yasg import openapi
from drf_yasg.utils import swagger_auto_schema
from rest_framework.views import APIView
from dvadmin.system.views.tasks import test_task, download_start

from application import dispatch

from dvadmin.utils.json_response import ErrorResponse, DetailResponse
import requests
from django.db import transaction
from dvadmin.system.models import DownloadList, DownloadInfo
from urllib.parse import unquote
from django_redis import get_redis_connection
import json


# 获取物流清单接口
class GetwayBillStatusList(APIView):
    authentication_classes = []
    permission_classes = []

    @swagger_auto_schema(
        responses={"200": openapi.Response("获取成功")},
        security=[],
        operation_id="getway-bill",
        operation_description="物流清单获取",
    )
    def get(self, request):
        token = request.headers["Authorization"]
        request_data = request.query_params
        start_time = request_data.get("start_time", "")
        end_time = request_data.get("end_time", "")
        type = request_data.get("type", "")

        type_dict = {
            "1": "发运中",
            "2": "已签收",
            "3": "审核",
            "4": "上传",
        }

        if not start_time or not end_time or not type:
            return ErrorResponse(code=4000, msg="接口参数异常")

        redis_conn = get_redis_connection()
        username_obj = redis_conn.get(f"login_token:{token}")
        if not username_obj:
            return ErrorResponse(code=4001, msg="登录失败")

        username_obj = username_obj.decode()

        yjdjzt = []
        if int(type) == 1 or int(type) == 2:
            yjdjzt.append(type_dict.get(type))
        elif int(type) == 3:
            yjdjzt.append('待审核')
            yjdjzt.append('审核通过')
            yjdjzt.append('审核不通过')
        elif int(type) == 4:
            yjdjzt.append('上传中')
            yjdjzt.append('上传成功')
            yjdjzt.append('上传失败')
        else:
            return ErrorResponse(code=4000, msg="接口参数异常")


        payload = {'beginTime': start_time + ' 00:00:00', 'endTime': end_time + ' 23:59:59',
                   'yjdjztList': yjdjzt}
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {token}"
        }
        response = requests.get('https://10.80.40.22:8443/apiv3/getwaybillyjdjlist', params=payload,
                                headers=headers, verify=False)
        rep_data = response.json()

        if rep_data["code"] in (400, 401):
            return ErrorResponse(code=401, msg={"code": "token_not_valid", "msg": "登录失效，请重新登陆"})
        return DetailResponse(data=rep_data["data"])


# 获取物流温度位置接口
class GetwayBillStatusInfo(APIView):
    authentication_classes = []
    permission_classes = []

    @swagger_auto_schema(
        responses={"200": openapi.Response("获取成功")},
        security=[],
        operation_id="getway-bill",
        operation_description="物流详细获取",
    )
    def get(self, request):
        token = request.headers["Authorization"]
        request_data = request.query_params
        ydh = request_data.get("ydh", "")

        if not ydh:
            return ErrorResponse(code=4000, msg="接口参数异常")

        redis_conn = get_redis_connection()
        username_obj = redis_conn.get(f"login_token:{token}")
        if not username_obj:
            return ErrorResponse(code=4001, msg="登录失败")

        username_obj = username_obj.decode()

        payload = {'ydh': ydh}
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {token}"
        }
        response = requests.get('https://wbr.solee56.com:8002/apiv4/getwaybilltemplist', params=payload,
                                headers=headers, verify=False)
        rep_data = response.json()

        if rep_data["code"] in (400, 401):
            return ErrorResponse(code=401, msg={"code": "token_not_valid", "msg": "登录失效，请重新登陆"})
        return DetailResponse(data=rep_data["data"]["rows"])


# 下载任务接口
class DownloadBill(APIView):
    authentication_classes = []
    permission_classes = []

    @swagger_auto_schema(
        responses={"200": openapi.Response("获取成功")},
        security=[],
        operation_id="download-file",
        operation_description="下载任务",
    )
    def get(self, request):
        token = request.headers["Authorization"]
        request_data = request.query_params
        download_checked = request_data.get("download_checked", "")
        ydh_list = request_data.get("ydh_list", "")

        if not download_checked or not download_checked:
            return ErrorResponse(code=4000, msg="接口参数异常")

        redis_conn = get_redis_connection()
        username_obj = redis_conn.get(f"login_token:{token}")
        if not username_obj:
            return ErrorResponse(code=4001, msg="登录失败")

        username_obj = username_obj.decode()

        payload = {'ydhList': ydh_list, 'fileType': download_checked}
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {token}"
        }

        response = requests.get('https://wbr.solee56.com:8002/apiv4/getwaybillfilelist', json=payload, headers=headers,
                                verify=False)
        rep_data = response.json()

        if rep_data["code"] in (400, 401):
            return ErrorResponse(code=401, msg={"code": "token_not_valid", "msg": "登录失效，请重新登陆"})

        username_obj = json.loads(username_obj)

        # 加入下载任务
        with transaction.atomic():
            for _data in rep_data["data"]["rows"]:
                list = DownloadList.objects.create(ydh=_data["ydh"], status=1, export_url="",
                                                   username=username_obj["username"])

                info_list_add = []
                for _info in _data["fileList"]:
                    info_list_add.append(DownloadInfo(ydh_id=list.id, file_url=unquote(_info), status=1))

                DownloadInfo.objects.bulk_create(info_list_add)

        # test_task.delay() todo
        download_start()
        return DetailResponse(data={})


# 下载任务列表接口
class DownloadListAll(APIView):
    authentication_classes = []
    permission_classes = []

    @swagger_auto_schema(
        responses={"200": openapi.Response("获取成功")},
        security=[],
        operation_id="download-file-list",
        operation_description="下载任务列表",
    )
    def get(self, request):
        token = request.headers["Authorization"]
        request_data = request.query_params
        page = int(request_data.get("page", 1))

        redis_conn = get_redis_connection()
        username_obj = redis_conn.get(f"login_token:{token}").decode()

        if not username_obj:
            return DetailResponse(data={}, msg="获取成功")

        redis_conn = get_redis_connection()
        username_obj = redis_conn.get(f"login_token:{token}")

        if not username_obj:
            return ErrorResponse(code=4001, msg="登录失败")

        username_obj = username_obj.decode()

        username_obj = json.loads(username_obj)

        page_size = 5
        count = DownloadList.objects.filter(username=username_obj["username"]).count()
        res = DownloadList.objects.filter(username=username_obj["username"]).all()[page_size*(page-1):page_size*page]

        return_data = []
        for item in res:
            _data = {}
            _data["ydh"] = item.ydh
            _data["status"] = item.status
            _data["create_datetime"] = item.create_datetime.strftime("%Y-%m-%d %H:%M:%S")
            _data["update_datetime"] = item.update_datetime.strftime("%Y-%m-%d %H:%M:%S")
            _data["export_url"] = item.export_url
            return_data.append(_data)

        return DetailResponse(data={"data":return_data,"count":count}, msg="获取成功")
